package com.yc.forum.util;

import com.google.gson.Gson;
import com.yc.forum.dao.RedisDao;
import sun.misc.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Utils {
    //增加用户num个积分点
    public static void addReward(String account,int num){
        RedisDao redisDao=new RedisDao();
        redisDao.updateReward(account,num+redisDao.getreward(account));
    }
    //删除html标签
    public static String takeOutHtmlTab(String htmlStr) {
        // 定义script的正则表达式，去除js可以防止注入
        String scriptRegex = "<script[^>]*?>[\\s\\S]*?<\\/script>";
        // 定义style的正则表达式，去除style样式，防止css代码过多时只截取到css样式代码
        String styleRegex = "<style[^>]*?>[\\s\\S]*?<\\/style>";
        // 定义HTML标签的正则表达式，去除标签，只提取文字内容
        String htmlRegex = "<[^>]+>";
        // 定义空格,回车,换行符,制表符
        String spaceRegex = "\\s*|\t|\r|\n";
        // 过滤script标签
        htmlStr = htmlStr.replaceAll(scriptRegex, "");
        // 过滤style标签
        htmlStr = htmlStr.replaceAll(styleRegex, "");
        // 过滤html标签
        htmlStr = htmlStr.replaceAll(htmlRegex, "");
        // 过滤空格等
        htmlStr = htmlStr.replaceAll(spaceRegex, "");
        // 过滤
        htmlStr = htmlStr.replace(" ", "");
        // 过滤
        htmlStr = htmlStr.replace(" ", "");
        // 返回文本字符串
        htmlStr = htmlStr.trim();
        // 去除空格" "
        htmlStr = htmlStr.replaceAll(" ", "");
        /*--------------------*/
        // 过滤空格等
        htmlStr = htmlStr.replaceAll("&nbsp;", "");
        return htmlStr;
    }

    public static void main(String[] args) {
        Utils utils = new Utils();
        String s= utils.takeOutHtmlTab("<p>asfds<font color=\"nibushi*-wodief9963b\">路漫漫其修远兮，吾将上下而求索。</font></p>");
        System.out.println("s="+s);
    }

    /**
     *将obj 转成json对象，通过相应对象返回给浏览器
     * @param obj
     * @param response
     */
    public static void toJson(Object obj, HttpServletResponse response) throws IOException {
        String json=new Gson().toJson(obj);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().append(json);
    }

    /**
     * 传入一个String日期格式，返回年月日
     * @param d
     */
    public static Map<String,Object> dateToYearMonthDay(String d){
        SimpleDateFormat sf =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Map<String,Object> map=new HashMap<>();
        try {
            Date date = sf.parse(d);
            //采纳javadoc的建议
            Calendar newDate = new GregorianCalendar();
            newDate.setTime(date);
            //分别将年，月，日放入
            map.put("year",newDate.get(Calendar.YEAR));
            map.put("month",newDate.get(Calendar.MONTH)+1);
            map.put("date",newDate.get(Calendar.DATE));
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("日期转换出错");
        }
        return map;
    }

    /**
     * 2.base64转图片
     * @param base64Code base64码
     * @param path   图片的名字
     * @return 返回图片路径
     */
    public static String convertBase64ToImage(String base64Code,String path,String path2) throws IOException {
        /**
         * 报错：java.lang.IllegalArgumentException: Illegal base64 character 20
         * 原因：base64编码时使用加号，在URL传递时加号会被当成空格让base64字符串更改，服务器端解码出错
         */
        String areaNames = base64Code.replaceAll(" ","+");

        System.out.println("---------init convertBase64ToImage()------------------");
        //获取图片的格式
        int begin=areaNames.indexOf("image/");
        int end=areaNames.indexOf(";");
        String imgFormat=path2+path+"."+areaNames.substring(begin+6,end);
        System.out.println(imgFormat+"=================imgFormat");
        System.out.println(imgFormat);
        FileOutputStream write = new FileOutputStream(new File(imgFormat));
        byte[] decoderBytes = Base64.getDecoder().decode(areaNames.split(",")[1]);
        write.write(decoderBytes);
        write.close();
        String path3="KFImgs"+"/"+path+"."+areaNames.substring(begin+6,end);
        System.out.println("path3================"+path3);
        return path3;
    }

    /**
     * String转Map  需要注意的是 value 值中 不能带 逗号(,)
     * @param param
     * @return
     */
    public static Map<String, Object> getValue(String param) {
        Map<String, Object> map = new HashMap<>();
        String str = "";
        String key = "";
        Object value = "";
        char[] charList = param.toCharArray();
        boolean valueBegin = false;
        for (int i = 0; i < charList.length; i++) {
            char c = charList[i];
            if (c == '{') {
                if (valueBegin == true) {
                    value = getValue(param.substring(i, param.length()));
                    i = param.indexOf('}', i) + 1;
                    map.put(key, value);
                }
            } else if (c == '=') {
                valueBegin = true;
                key = str;
                str = "";
            } else if (c == ',') {
                valueBegin = false;
                value = str;
                str = "";
                map.put(key, value);
            } else if (c == '}') {
                if (str != "") {
                    value = str;
                }
                map.put(key, value);
                return map;
            } else if (c != ' ') {
                str += c;
            }
        }
        return map;
    }


}
